import { defineStore } from "pinia";
import { getCityList } from "../api/cityList";

export const useCityStore = defineStore("city", {
  state: () => ({
    // 存放接口返回的城市列表数据
    rawCitys: [],
    // 当前选择的城市
    curCity: { cityId: 440300, isHot: 1, name: "深圳", pinyin: "shenzhen" },
  }),

  getters: {
    // 用于 城市选择页面的展示数据
    citys: (state) => {
      const { rawCitys } = state;
      // 存放最终结果
      let result = [];
      // 遍历 rawCitys
      rawCitys.forEach((city) => {
        // 取出当前 city 的拼音首字母大写
        let anchor = city.pinyin.substr(0, 1).toUpperCase();

        // 判断当前这个 anchor 在 result 中是否存在
        const obj = result.find((item) => item.anchor === anchor);
        if (obj) {
          // console.log("obj", obj);
          obj.citys.push(city);
        } else {
          // 写入 result, 新增一项
          result.push({
            anchor: anchor,
            citys: [city],
          });
        }
      });
      return result.sort((a, b) => {
        return a.anchor.charCodeAt(0) - b.anchor.charCodeAt(0);
      });
    },

    indexList() {
      return this.citys.map((item) => item.anchor);
    },

    curCityId: (state) => state.curCity.cityId,
  },

  actions: {
    fetchRawCitys() {
      getCityList().then((res) => {
        this.rawCitys = res.data.cities;
      });
    },

    changeCurCity(city) {
      this.curCity = city;
    },
  },
});
